// stores/user.js - 用户状态管理
import { defineStore } from 'pinia'
import request from '@/utils/request'
import router from '@/router'

export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: null,
    }),

    getters: {
        isLoggedIn: (state) => !!state.token,
    },

    actions: {
        // 登录
        async login(loginData) {
            try {
                const response = await request.post('/auth/login', {
                    username: loginData.username,
                    password: loginData.password
                }, {
                    loading: true,
                    loadingText: '登录中...'
                })

                if (response.code === 200) {
                    const token = response.data.token
                    const userInfo = response.data.userInfo

                    // 保存token
                    this.token = token
                    this.userInfo = userInfo

                    // 持久化存储
                    if (loginData.rememberMe) {
                        localStorage.setItem('token', token)
                        localStorage.setItem('userInfo', JSON.stringify(userInfo))
                    } else {
                        sessionStorage.setItem('token', token)
                        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
                    }

                    return response
                } else {
                    throw new Error(response.message || '登录失败')
                }
            } catch (error) {
                console.error('登录错误:', error)
                throw error
            }
        },

        // 获取用户信息
        async getUserInfo() {
            try {
                const response = await request.get('/auth/userinfo')

                if (response.code === 200) {
                    this.userInfo = response.data.userInfo

                    // 更新存储
                    const storage = localStorage.getItem('token') ? localStorage : sessionStorage
                    storage.setItem('userInfo', JSON.stringify(this.userInfo))

                    return response.data
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                // 如果获取用户信息失败，可能token已过期，执行登出
                this.logout()
                throw error
            }
        },

        // 刷新token
        async refreshToken() {
            try {
                const response = await request.post('/auth/refresh-token')

                if (response.code === 200) {
                    const token = response.data.token
                    this.token = response.data.token

                    // 更新存储
                    const storage = localStorage.getItem('token') ? localStorage : sessionStorage
                    storage.setItem('token', token)

                    return token
                }
            } catch (error) {
                console.error('刷新token失败:', error)
                this.logout()
                throw error
            }
        },

        // 登出
        async logout() {
            try {
                // 调用后端登出接口
                await request.post('/auth/logout', {}, {
                    loading: false // 登出不需要loading
                })
            } catch (error) {
                console.error('登出接口调用失败:', error)
            } finally {
                // 清除本地状态
                this.token = ''
                this.userInfo = null

                // 清除存储
                localStorage.removeItem('token')
                localStorage.removeItem('userInfo')
                sessionStorage.removeItem('token')
                sessionStorage.removeItem('userInfo')

                // 重定向到登录页
                router.push('/login')
            }
        },

        // 初始化用户状态（页面刷新时调用）
        initUserState() {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token')
            const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')

            if (token) {
                this.token = token
                this.userInfo = userInfo ? JSON.parse(userInfo) : null
            }
        },
    }
})